﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using StockUtil;

namespace StockLib.Data
{
    public class CodeFileSaver
    {
        /// <summary>
        /// 保存代码表
        /// </summary>
        public virtual void Save()
        {
            //Trace.WriteLine("StockCodeFileSaver.Save");
            foreach (StockMarket market in StockProfile.Markets)
            {
                Save(market);
            }
        }

        /// <summary>
        /// 保存特定市场代码表
        /// </summary>
        /// <param name="market">市场类型</param>
        private void Save(StockMarket market)
        {
            FileInfo fi = new FileInfo(StockData.Instance.GetFileName(market, DataType.Code));
            FileStream fs = null;

            try
            {
                if (!fi.Directory.Exists)
                    Directory.CreateDirectory(fi.Directory.FullName);

                fs = new FileStream(fi.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                foreach (Stock stock in StockContainer.Instance.Values)
                {
                    if (stock.Market == market)
                    {
                        CodeFilePack pack = CodeFilePack.FromInternal(stock);
                        byte[] buffer = StructHelper.ToBytes(pack);
                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
